package com.hzzc.core.service;

import com.hzzc.BizException;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.security.MessageDigest;

/**
 * @author zmm
 * 密码加密器：基于MD5算法实现
 */
@Component
public class PasswdEncoder {

    /**
     * Md5Encoder
     *
     * @param string
     * @return
     * @throws Exception
     */
    public String encode(String string) throws BizException {

        try {
            if(StringUtils.isEmpty(string)){
                string="";
            }
            byte[] hash = new byte[0];
            hash = MessageDigest.getInstance("MD5").digest(string.getBytes("UTF-8"));
            StringBuilder hex = new StringBuilder(hash.length * 2);
            for (byte b : hash) {
                if ((b & 0xFF) < 0x10) {
                    hex.append("0");
                }
                hex.append(Integer.toHexString(b & 0xFF));
            }
            return hex.toString();
        } catch (Exception e) {
            throw new BizException("密码加密错误！", e);
        }
    }

}
